<script type="text/javascript">
$(function() {
  var lat = $('input[name$="[lat]"]');
  var lng = $('input[name$="[lng]"]');
  var marker, ll, map;

  function loadMap() {
    if (lat.val() && lng.val()) {
      ll = new google.maps.LatLng(lat.val(), lng.val());
    } else {
      ll = new google.maps.LatLng(-34.397, 150.644);
    }
    var opt = {
      zoom: 8,
      center: ll,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    }
    var el = $("#map-container");
        map = new google.maps.Map(document.getElementById("map-container"), opt);

    google.maps.event.addListener(map, 'click', function(event) {
      if ( marker === undefined ) {
        placeMarker(event.latLng);
      }
    });
    if (lat.val() && lng.val()) {
      placeMarker(ll);
    }
  }

  function placeMarker(location) {
    marker = new google.maps.Marker({
      position: location,
      map: map,
      draggable:true,
      animation: google.maps.Animation.DROP
    });
    map.setCenter(location);

    google.maps.event.addListener(marker, 'dragend', function() {
      map.setCenter(marker.position);
      lat.val(marker.position.lat());
      lng.val(marker.position.lng());
    });
  }
  loadMap();
});
</script>
